package lib.self.utils;

import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.util.Timer;
import java.util.TimerTask;

/**
 * description: 输入法管理器
 * author: Steven Xiao
 * date: 2017/6/22
 */
public class InputUtil {
    /**
     * 隐藏虚拟键盘
     */
    public static void hideKeyboard(View v) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    /**
     * 掩饰隐藏输入法
     */
    public static void hideKeyboardDelay(View view, long delay) {
        new Handler().postDelayed(() -> InputUtil.hideKeyboard(view), delay);
    }

    /**
     * 显示虚拟键盘
     */
    public static void showKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 强制显示或者关闭系统键盘(显示则隐藏 隐藏则显示)
     */
    public static void showKeyBoard(EditText editText) {
        new Handler().postDelayed(() -> {
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            editText.requestFocus();
            InputUtil.showKeyboard(editText);
        }, 300);
    }

    /**
     * 通过定时器强制隐藏虚拟键盘
     */
    public static void timerHideKeyboard(final View v) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
            }
        }, 10);
    }

    /**
     * 输入法是否显示着
     */
    public static boolean isShowKeyboard(EditText edittext) {
        InputMethodManager imm = (InputMethodManager) edittext.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            return true;
        }
        return false;
    }
}
